/**
 * @author yxw
 * date : 2013年11月3日 下午10:29:25 
 */
package com.tzinfo.tzt.activity;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.view.ViewPager;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.tzinfo.tzt.R;
import com.tzinfo.tzt.activity.util.MyApplication;
import com.tzinfo.tzt.activity.view.ImagePagerAdapter;
import com.tzinfo.tzt.activity.view.MyProgressDialog;
import com.tzinfo.tzt.activity.view.VerticalScrollView;
import com.tzinfo.tzt.config.AppDataConfig;
import com.tzinfo.tzt.domain.MyResultList;
import com.tzinfo.tzt.domain.RenthouseVillage;
import com.tzinfo.tzt.service.HouseHistoryService;
import com.tzinfo.tzt.util.HttpTools;
import com.tzinfo.tzt.util.JsonTools;

public class RenthouseVillageAcitivity extends BaseActivity implements
		OnClickListener {

	// 传递数据
	private int villageId;

	// 工具类
	private List<Map<String, Object>> imgData;
	private Dialog dialog;
	private MyResultList jsonResult;
	private ImageLoader imageLoader = ImageLoader.getInstance();
	private Intent thisIntent;
	private RenthouseVillage detail;
	private DisplayImageOptions options;
	private RelativeLayout mapLayout;

	// UI组件
	private Button backBtn;
	private VerticalScrollView mScrollView;
	private ImageView mapView, noPicView;
	private TextView[] textViews = new TextView[9];
	private ViewPager imagesPager;
	private ImagePagerAdapter imagePagerAdapter;
	private RelativeLayout oldHouseLayout;
	

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_rentvillage_detail);
		thisIntent=this.getIntent();
		villageId = thisIntent.getIntExtra("villageId", 0);
		init();

	}

	private void init() {

		noPicView = (ImageView) this.findViewById(R.id.img_no_Village_images);
		backBtn = (Button) this.findViewById(R.id.bt_back);
		backBtn.setOnClickListener(this);
		
		
		mapLayout = (RelativeLayout) this
				.findViewById(R.id.layout_house_location);
		mapLayout.setOnClickListener(this);
		// layout
		oldHouseLayout = (RelativeLayout) this
				.findViewById(R.id.layout_same_community_second);
		oldHouseLayout.setOnClickListener(this);

		// Infos
		textViews[0] = (TextView) this.findViewById(R.id.text_Village_Name);
		textViews[1] = (TextView) this
				.findViewById(R.id.text_Village_HouseCount);
		textViews[2] = (TextView) this.findViewById(R.id.text_Village_Address);
		textViews[3] = (TextView) this
				.findViewById(R.id.text_Village_BuildType);
		textViews[4] = (TextView) this
				.findViewById(R.id.text_Village_BuildYear);

		textViews[5] = (TextView) this
				.findViewById(R.id.text_Village_Address2);
		// 显示地图控件
		mapView = (ImageView) this.findViewById(R.id.img_Village_Address);
		textViews[6] = (TextView) this
				.findViewById(R.id.text_Village_Describe);
		textViews[7] = (TextView) this
				.findViewById(R.id.text_Village_LifeSupport);
		textViews[8] = (TextView) this
				.findViewById(R.id.text_Village_Info);

		options = new DisplayImageOptions.Builder()
				.showImageOnLoading(R.drawable.ic_stub)
				.showImageForEmptyUri(R.drawable.ic_empty)
				.showImageOnFail(R.drawable.ic_error).cacheInMemory(true)
				.cacheOnDisc(true).bitmapConfig(Bitmap.Config.RGB_565).build();
		imagesPager = (ViewPager) this.findViewById(R.id.pager_Village_images);
		dialog = new MyProgressDialog(this).createDialog(getResources()
				.getString(R.string.loading));
		// 加载进度条
		dialog.show();
		mScrollView = (VerticalScrollView) this.findViewById(R.id.scrollview);
		mScrollView.smoothScrollTo(0, 0);
		new Thread(getRenthouseVillageDetailRun).start();
	}

	private void getDataError(String ERRORMESSAGE) {
		new AlertDialog.Builder(this).setCancelable(false)
				.setMessage(ERRORMESSAGE)
				.setPositiveButton(getResources().getString

				(R.string.cancel), new DialogInterface.OnClickListener()

				{
					public void onClick

					(DialogInterface dialog, int which) {
						finish();
					}
				}).setNegativeButton(getResources().getString

				(R.string.try_again), new DialogInterface.OnClickListener()

				{
					public void onClick(

					DialogInterface dialogInterface, int

					whichButton) {
						dialog.show();
						new Thread(getRenthouseVillageDetailRun).start();
					}
				}).show();
	}

	@SuppressLint("HandlerLeak")
	Handler handler = new Handler() {
		public void handleMessage(Message msg) {
			super.handleMessage(msg);
			switch (msg.arg1) {
			case 1:
				updateUI();
				dialog.dismiss();
				break;
			case -1:
				getDataError((String) msg.obj);
				break;
			case 5:
				break;
			case 7:
				break;
			case 0:
				break;
			}
		}
	};

	/**
	 * 线程 得到新房列表
	 */
	Runnable getRenthouseVillageDetailRun = new Runnable() {

		@Override
		public void run() {
			Message msg = handler.obtainMessage();
			if(villageId!=-1){
				String jsonString;
				String url=AppDataConfig.zufangUrl
						+ AppDataConfig.RenthouseVillage + "?id=" + villageId;
				Log.e("url", url);
				jsonString = HttpTools.getJsonContent(url);
				Log.e("JsonString", jsonString);
				jsonResult = JsonTools.getRenthouseVillage(jsonString);
			}else{
				jsonResult=new MyResultList();
				jsonResult.setSuccess(false);
				jsonResult.setErrorMessage("抱歉，没有该小区信息！");
			}
			getData();
			if (jsonResult.getSuccess()) {
				msg.arg1 = 1;
			} else {
				msg.arg1 = -1;
				msg.obj = jsonResult.getErrorMessage();
			}
			handler.sendMessage(msg);
		}
	};

	// 得到data数据
	private void getData() {
		imgData = new ArrayList<Map<String, Object>>();
		Map<String, Object> map;
		if (jsonResult.getSuccess()) {
			detail = (RenthouseVillage) jsonResult.getData().get(0);
			List<String> pics = detail.getPics();
			if (pics == null || pics.size() == 0) {
				map = new HashMap<String, Object>();
				map.put("img", R.drawable.ic_empty);
				imgData.add(map);
			}
			for (int i = 0; i < pics.size(); i++) {
				map = new HashMap<String, Object>();
				map.put("img", pics.get(i));
				imgData.add(map);
			}

		}
	}
	
	private void updateUI() {
		if(detail.getPics().size()==0){
			imagesPager.setVisibility(View.GONE);
			noPicView.setVisibility(View.VISIBLE);
		}
		imagePagerAdapter = new ImagePagerAdapter(this, imgData,
				R.layout.item_pager_image, new String[] { "img" },
				new int[] { R.id.image });
		imagesPager.setAdapter(imagePagerAdapter);
		imagesPager.setCurrentItem(0);

		// getInfos
		textViews[0].setText(detail.getName());
		
		textViews[1].setText(detail.getHouseCount()+"套");
		textViews[2].setText(detail.getAddress());
		textViews[3].setText(detail.getBuildType());
		textViews[4].setText(detail.getBuildYear());
		textViews[5].setText(detail.getAddress());
		String describe = detail.getDescribe();
		if (describe == null || "".equals(describe.trim())) {
			describe = "该小区目前没有描述！";
		}
		textViews[6].setText(describe);
		
		String lifeSupport = detail.getLifeSupport();
		if (lifeSupport == null || "".equals(lifeSupport.trim())) {
			lifeSupport = "该小区目前没有生活配套的信息！";
		}
		textViews[7].setText(lifeSupport);
		
		String info = detail.getLifeSupport();
		if (info == null || "".equals(info.trim())) {
			info = "该小区目前没有周边信息！";
		}
		textViews[8].setText(info);

		// 显示百度地图
		String mapUrl = "http://api.map.baidu.com/staticimage?center="
				+ detail.getLon() + ","
				+ detail.getLat() + "&width="
				+ MyApplication.widthPixels + "&height="
				+ MyApplication.widthPixels * 0.75 + "&zoom=12";
		imageLoader.displayImage(mapUrl, mapView, options);
		
		mScrollView.smoothScrollTo(0, 0);
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.bt_back:
			this.finish();
			break;
		case R.id.layout_same_community_second:
			Intent samecommunityIntent = new Intent(this,RentSameCommunityListActivity.class);
			samecommunityIntent.putExtra("villageId", detail.getID());
			samecommunityIntent.putExtra("villageName", detail.getName());
			startActivity(samecommunityIntent);
			break;
		case R.id.layout_house_location:
			Intent mapIntent = new Intent(this, MapRoutePlanActivity.class);
			mapIntent.putExtra("lon", detail.getLon());
			mapIntent.putExtra("lat", detail.getLat());
			mapIntent.putExtra("houseName", detail.getName());
			startActivity(mapIntent);
			break;
		}

	}
}
